import * as menuService from "../services/menuService"
import {PAGE_SIZE} from "../components/constants";
import {message} from "antd";
import {routerRedux} from 'dva/router';

export default {
  namespace: "menu",
  state: {
    dataList: [],
    total: 0,
    page: 1,
    pageSize: PAGE_SIZE
  },
  effects: {
    * fetch({payload: {page = 1, pageSize = PAGE_SIZE}}, {put, call}) {
      const {data} = yield call(menuService.list, {page, pageSize});
      yield put({
        type: "loadMenus",
        payload: {
          dataList: data.recordset,
          total: data.recordset.length,
          page: page,
          pageSize: pageSize
        }
      });
    },
    * detail({payload: {id}}, {put, call}) {
      const {data} = yield call(menuService.detail, {id});
      yield put({
        type: "loadDetail",
        payload: {
          data: data
        }
      });
    },
    * update({payload: {data}}, {put, call}) {
      const {success, errorMsg} = yield call(menuService.update, {data});
      if (success) {
        message.success("保存成功!");
        yield put(routerRedux.push('/menu'));
      } else if (errorMsg) {
        message.error("保存失败:" + errorMsg);
      }
    }
  },
  reducers: {
    loadMenus(state, {payload: {dataList, total, page, pageSize}}) {
      console.log("load list");
      return {...state, dataList, total, page, pageSize};
    },
    loadDetail(state, {payload: {data}}) {
      console.log("load detail");
      return {...state, data};
    }
  }
}
